#include "include.h"
#include "api.h"


void bt_new_name_init(void);


/********************************************************/
extern void bt_tws_set_operation(uint8_t *cmd);

#if BT_2ACL_EN
extern bool cfg_bt_disconnect_a2dp_playing;
void bt_2acl_switch_music_play_next(void)              //一拖二时，在两台设备之间切换播放
{
    bt_2acl_switch_music_play();
    bt_music_play_pause();
}
void bt_disconnect_a2dp_playing(void)
{
    cfg_bt_disconnect_a2dp_playing = true;
    bt_disconnect(1);
    cfg_bt_disconnect_a2dp_playing = false;
}
void bt_2acl_scan_second_device(void)
{
    cfg_bt_scan_ctrl_mode = true;
    bt_set_scan(true, true);        //长按5S开机，直接进bt scanning
    cfg_bt_scan_ctrl_mode = false;
}
#endif // BT_2ACL_EN
#if 0
//是否支持android & ios播放暂停快速切换，需要时定义该函数
//注意：打开后ios播放微信小视频会无声，播放器听音乐不影响
//      部分android4.0及之前系统打开多个播放器可能有兼容问题
bool bt_force_super_fast_status(void)
{
    return true;
}
#endif

#if 0
//是否支持ios播放暂停快速切换，需要时定义该函数，蓝牙后台建议打开
//注意：打开后ios播放微信小视频会无声，播放器听音乐不影响
bool bt_support_ios_fast_status(void)
{
    return true;
}
#endif


//
//bool bt_is_force_master(void)
//{
//    if ((!BT_TWS_EN) || (!xcfg_cb.bt_tws_en)){
//        return false;
//    } else {
//        return true;
//    }
//}
//
//void lm_set_diac_lap_do(u8 enable);
//volatile u8 wireless_mic_en = 0;
//void lm_set_diac_lap(void)
//{
//    lm_set_diac_lap_do(wireless_mic_en);
//}

void bsp_bt_init(void)
{
    //更新配置工具的设置
    cfg_bt_rf_def_txpwr = xcfg_cb.bt_txpwr;
    cfg_bt_page_inq_txpwr = xcfg_cb.bt_rf_txpwr_recon;

    cfg_bt_support_profile = (PROF_A2DP*BT_A2DP_EN*xcfg_cb.bt_a2dp_en) | (PROF_HFP*BT_HFP_EN*xcfg_cb.bt_sco_en)\
                            | (PROF_SPP*BT_SPP_EN*(xcfg_cb.bt_spp_en||xcfg_cb.eq_dgb_spp_en)) | (PROF_HID*BT_HID_EN*xcfg_cb.bt_hid_en) | (PROF_PBAP*BT_PBAP_EN);
#if BT_A2DP_VOL_CTRL_EN
    if(!xcfg_cb.bt_a2dp_vol_ctrl_en) {
        cfg_bt_a2dp_feature &= ~A2DP_VOL_CTRL;
    } else {
        cfg_bt_a2dp_feature |= A2DP_VOL_CTRL;
    }
#endif
    cfg_bt_dual_mode = BT_DUAL_MODE_EN;
    cfg_bt_max_acl_link = BT_2ACL_EN * xcfg_cb.bt_2acl_en + 1;
#if BT_TWS_EN
    cfg_bt_tws_mode = BT_TWS_EN * xcfg_cb.bt_tws_en;
    cfg_bt_tws_pair_mode &= ~0x0f;
    cfg_bt_tws_pair_mode |= xcfg_cb.bt_tws_pair_mode & 0x0f;
    if(!cfg_bt_tws_mode){
        cfg_bt_tws_feat = 0;
    }

    if(xcfg_cb.bt_tws_lr_mode > 8) {    //开机时PWRKEY可能按住，先不检测
        tws_lr_xcfg_sel();
    }
#endif
#if BT_HFP_EN
    if(!xcfg_cb.bt_hfp_ring_number_en) {
        cfg_bt_hfp_feature &= ~HFP_RING_NUMBER_EN;
    }
#endif

#if BT_TWS_AUTO_SWITCH
    if(xcfg_cb.bt_tswi_en) {
        cfg_bt_tws_feat |= TWS_FEAT_MS_SWITCH;
    } else {
        cfg_bt_tws_feat &= ~TWS_FEAT_MS_SWITCH;
    }
#endif

#if BT_FCC_TEST_EN
    bt_fcc_init();
#endif

#if FUNC_BTHID_EN
    if (is_bthid_mode()) {
        cfg_bt_support_profile = PROF_HID;
        cfg_bt_max_acl_link = 1;
        cfg_bt_dual_mode = 0;
        cfg_bt_tws_mode = 0;
    }
#endif // FUNC_BTHID_EN

    memset(&f_bt, 0, sizeof(func_bt_t));
    f_bt.disp_status = 0xfe;
    f_bt.need_pairing = 1;  //开机若回连不成功，需要播报pairing
    if (!is_bthid_mode()) {
        f_bt.hid_menu_flag = 1;
    }

    bt_setup();
}

void bsp_bt_close(void)
{
}

#if BT_PWRKEY_5S_DISCOVER_EN
bool bsp_bt_w4_connect(void)
{
    if (xcfg_cb.bt_pwrkey_nsec_discover) {
        while (sys_cb.pwrkey_5s_check) {            //等待检测结束
            WDT_CLR();
            delay_5ms(2);
        }

        //已检测到长按5S，需要直接进入配对状态。播放PAIRING提示音。
        if (sys_cb.pwrkey_5s_flag) {
            return false;
        }
    }
    return true;
}

bool bsp_bt_pwrkey5s_check(void)
{
    bool res = !bsp_bt_w4_connect();
    delay_5ms(2);
    return res;
}

void bsp_bt_pwrkey5s_clr(void)
{
    if (!xcfg_cb.bt_pwrkey_nsec_discover) {
        return;
    }
    sys_cb.pwrkey_5s_flag = 0;
#if !BT_DISCOVER_CTRL_EN    //使用按键打开可被发现时scan_ctrl=1
    cfg_bt_scan_ctrl_mode = 0;   //scan_ctrl=0，则连接断开后会自动打开可被发现
#endif
}
#endif // BT_PWRKEY_5S_DISCOVER_EN

void bsp_bt_vol_change(void)
{
#if BT_A2DP_VOL_CTRL_EN || BT_TWS_EN
    if((xcfg_cb.bt_a2dp_vol_ctrl_en && (bt_get_status() >= BT_STA_CONNECTED)) || bt_tws_is_connected()) {
        bt_music_vol_change();     //通知手机音量已调整
    }
#endif
}

uint bsp_bt_get_hfp_vol(uint hfp_vol)
{
    uint vol;
    vol = (hfp_vol + 1) * sys_cb.hfp2sys_mul;
    if (vol > VOL_MAX) {
        vol = VOL_MAX;
    }
    return vol;
}

//extern u8 addr_buf[6];
//u8 bt_addr_buf[6];
uint8_t bt_get_connect_addr(uint8_t *bd_addr);//根据地址回连手机，可不调用bt_connect（）；
void bt_emit_notice(uint evt, u32 param)
{
//    static u8 bt_order;     //回连第n个手机
//    if (bt_order == 3) bt_order = 0;    //测试最多只支持保存4部手机
	printf("bt evt:%d\n",evt);
    switch(evt) {
    case BT_NOTICE_INIT_FINISH:
#if WORK_MODE != MODE_BQB_RF
#if BT_PWRKEY_5S_DISCOVER_EN
        if(bsp_bt_w4_connect()) {
            bt_connect(BT_POWER_UP_RECONNECT_TIMES);
        } else {
            cfg_bt_scan_ctrl_mode = 1;
            bt_set_scan(true, true);        //长按5S开机，直接进bt scanning
        }
#else
		if(bt_nor_get_link_info(NULL))
		{
			//bt_connect(BT_POWER_UP_RECONNECT_TIMES);
		}
        
#endif
#endif
    case BT_NOTICE_CONNECT_START:
		#if 0
		if(bt_nor_get_link_info(NULL))
		{
			bt_connect(BT_TIME_OUT_RECONNECT_TIMES);
			msg_enqueue(EVT_BT_RECONNECT);
		}	
		#endif
		break;
	case BT_NOTICE_CONNECT_FAIL:
		msg_enqueue(EVT_BT_RECONNECT_FAIL);
		break;
//        bt_nor_get_link_info_addr(addr_buf, bt_order);
//        bt_get_connect_addr(bt_addr_buf);
//        bt_connect_address();
        break;

//    case BT_NOTICE_CONNECT_START://开始回连手机, param[0]=nouse,  param[6:1]=bd_addr
//            my_printf("bt_star:%d\n",((u8 *)param)[0]);
//            my_print_r((u8 *)param, 7);
//        break;
//
//    case BT_NOTICE_CONNECT_FAIL://回连手机失败, param[0]=reason, param[6:1]=bd_addr
//            my_printf("bt_fail:%d\n",((u8 *)param)[0]);
//            my_print_r((u8 *)param, 7);
//            if (bt_order == 0) bt_order += 1;
//            bt_nor_get_link_info_addr(addr_buf, bt_order);
//            bt_get_connect_addr(bt_addr_buf);
//            bt_connect_address();
//
//        break;

    case BT_NOTICE_DISCONNECT:
        f_bt.warning_status |= BT_WARN_DISCON;
        bt_redial_reset(((u8 *)param)[0] & 0x01);
        delay_5ms(5);
        break;
    case BT_NOTICE_CONNECTED:
        f_bt.warning_status |= BT_WARN_CON;
        bt_redial_reset(((u8 *)param)[0] & 0x01);
#if BT_PWRKEY_5S_DISCOVER_EN
        bsp_bt_pwrkey5s_clr();
#endif // BT_PWRKEY_5S_DISCOVER_EN
        delay_5ms(5);
        break;

    case BT_NOTICE_LOSTCONNECT:
		//printf("=====================>bt lost connect\n")
		//bt_connect(BT_TIME_OUT_RECONNECT_TIMES);
		//bt_abort_reconnect();		
		cfg_bt_scan_ctrl_mode = 1;
        bt_set_scan(false, true);        //长按5S开机，直接进bt scanning
       // delay_5ms(20);
		//bt_connect(8);
		msg_enqueue(EVT_BT_LOSSCONNECT);
        break;
//    case BT_NOTICE_INCOMING:
//    case BT_NOTICE_RING:
//    case BT_NOTICE_OUTGOING:
//    case BT_NOTICE_CALL:
//        break;

	case BT_NOTICE_RECON_FINISH:
		//msg_enqueue(EVT_BT_RECONNECT_FINISH);
		break;
	case BT_NOTICE_ABORT_STATUS:
		break;
    case BT_NOTICE_SET_SPK_GAIN:
		if(sys_cb.vol_sync_to_remote||bt_get_disp_status() == BT_STA_INCOMING)
		{
			printf("hfp wait sync to remote first!!\n");
			break;
		}
        if(param != sys_cb.hfp_vol) {
            sys_cb.hfp_vol = param;
            msg_enqueue(EVT_HFP_SET_VOL);
        }
        break;

    case BT_NOTICE_MUSIC_PLAY:
        msg_enqueue(EVT_A2DP_MUSIC_PLAY);
        break;
	case BT_NOTICE_SCO_SETUP:
		msg_enqueue(EVT_SCO_START);
		break;
	case BT_NOTICE_SCO_FAIL:
	case BT_NOTICE_SCO_KILL:
		msg_enqueue(EVT_SCO_END);
		break;
    case BT_NOTICE_MUSIC_STOP:
        if (bt_get_disp_status() > BT_STA_PLAYING) {
            break;
        }
        msg_enqueue(EVT_A2DP_MUSIC_STOP);
        break;

    case BT_NOTICE_MUSIC_CHANGE_VOL:
        if(param == 0) {
            msg_enqueue(KU_VOL_DOWN);
        } else {
            msg_enqueue(KU_VOL_UP);
        }
        break;
    case BT_NOTICE_HID_CONN_EVT:
#if BT_HID_MANU_EN
        if (xcfg_cb.bt_hid_menu_en) {
            if (f_bt.hid_menu_flag == 2) {
                //按键连接/断开HID Profile完成
                if (param) {
                    f_bt.warning_status |= BT_WARN_HID_CON;
                } else {
                    f_bt.warning_status |= BT_WARN_HID_DISCON;
                }
                f_bt.hid_menu_flag = 1;
            }
    #if BT_HID_DISCON_DEFAULT_EN
            else if (f_bt.hid_menu_flag == 1) {
                if ((param) & (xcfg_cb.bt_hid_discon_default_en)) {
                    f_bt.hid_discon_flag = 1;
                }
            }
    #endif // BT_HID_DISCON_DEFAULT_EN
        }
#endif // BT_HID_MANU_EN
        break;

#if BT_TWS_EN
//    case BT_NOTICE_TWS_SEARCH_TIMEOUT:
//        break;
//    case BT_NOTICE_TWS_CONNECT_START:
//        break;
    case BT_NOTICE_TWS_DISCONNECT:
        f_bt.tws_status = 0;
        f_bt.warning_status |= BT_WARN_TWS_DISCON;      //TWS断线不播报提示音，仅更改声道配置
        break;
    case BT_NOTICE_TWS_CONNECTED:
        f_bt.tws_status = ((u8 *)param)[0];
        if(f_bt.tws_status & 0x08) {
            f_bt.warning_status |= BT_WARN_TWS_CON;     //无连接提示音，仅更改声道配置
        } else if(f_bt.tws_status & 0x80) {
            f_bt.warning_status |= BT_WARN_TWS_SCON;    //TWS连接提示音
        } else {
            f_bt.warning_status |= BT_WARN_TWS_MCON;    //TWS连接提示音
        }
        break;
    case BT_NOTICE_TWS_LOSTCONNECT:
        break;
    case BT_NOTICE_TWS_RES_PLAY:
        sys_cb.tws_res_brk = 1;    //打断当前提示音
        tws_res_add(*(u8 *)param, *(u32 *)(param+1));
        break;

    case BT_NOTICE_TWS_HID_SHUTTER:
        msg_enqueue(EVT_TWS_HID_SHUTTER);
        break;

    case BT_NOTICE_TWS_SET_VOL:
        param = (param+1) * VOL_MAX / 128;
        sys_cb.vol = param;
        if (sys_cb.vol > VOL_MAX) {
            sys_cb.vol = VOL_MAX;
        }
        msg_enqueue(EVT_TWS_SET_VOL);
        break;

    //TWS自定义按键,通过bt_tws_user_key函数发送
    case BT_NOTICE_TWS_USER_KEY:
        if (param == 0x101) {
            f_bt.ring_stop = 1;
        }
        break;
#endif

    case BT_NOTICE_MUSIC_SET_VOL:
		if(sys_cb.vol_sync_to_remote)
		{
			printf("wait sync to remote first!!\n");
			break;
		}
        param = (param+1) * VOL_MAX / 128;
        if(param != sys_cb.vol) {
            sys_cb.vol = param;
            if (sys_cb.vol > VOL_MAX) {
                sys_cb.vol = VOL_MAX;
            }
            msg_enqueue(EVT_A2DP_SET_VOL);
        }
        break;

    }
}

#if BT_TWS_EN
//TWS蓝牙名称是否增加_L或_R后缀
void bt_name_suffix_set(void)
{
    sys_cb.name_suffix_en = 0;
    if (xcfg_cb.bt_tws_name_suffix_en) {
        if ( (xcfg_cb.bt_tws_lr_mode < 9) ||
             (xcfg_cb.bt_tws_lr_mode == 9 && xcfg_cb.tws_sel_left_gpio_sel == 0) ) {
            return;
        }

        if (strlen(xcfg_cb.bt_name) < 30) {
            if (sys_cb.tws_left_channel) {
                strcat(xcfg_cb.bt_name, "L");
            } else {
                strcat(xcfg_cb.bt_name, "R");
            }
            sys_cb.name_suffix_en = 1;
            printf("bt_name_suffix: %s\n", xcfg_cb.bt_name);
        }
    }
}
#endif // BT_TWS_EN


#if (FUNC_FCC_MODE_EN && 1)   //FCC产测试数据回调打印对比
void fcc_param_print(struct vs_test_ctrl_cmd  const *param)
{
    my_printf("\nFCC------------------------------------------------>\n");
    my_printf("mode(0 is fcc) = %d\n",param->mode);
    my_printf("test_scenario = %d\n",param->test_scenario);
    my_printf("hopping_mode = %d\n",param->hopping_mode);
    my_printf("tx_freq = %d\n",param->tx_freq);
    my_printf("rx_freq = %d\n",param->rx_freq);
    my_printf("power_control = %d\n",param->power_control);
    my_printf("poll_period = %d\n",param->poll_period);
    my_printf("packet_type = %d\n",param->packet_type);
    my_printf("payload_length = %d\n\n",param->payload_length);
}
#endif
